<template>
	<!-- Cascader 级联选择器 -->
    <el-cascader :value="cascaderValue" :placeholder="placeholder" :options="options" :props="props" :style="{width: '100%'}"
      @change="handleChange" filterable clearable>
    </el-cascader>
</template>

<script>
  export default {
    model: {
      prop: '_inputValue',
      event: 'input'
    },
    props: {
      _inputValue: null,
      options: Array,
      props: Object,
      placeholder: String,
    },
    data() {
      return {
        cascaderValue: [],
        value: [],
      }
    },
    mounted() {
      this.settingIndex();
      this.setValue();
    },
    methods: {
      setValue() {
        var ps = [];
        this._inputValue.forEach(x => {
          var index = this.findPath(x);
          if (index) ps.push(index.split("  "));
        })
        this.cascaderValue = ps;
        this.value = this._inputValue;
      },
      handleChange() {
        var vals = [];
        this.cascaderValue.forEach(x => vals.push(x[x.length - 1]));
        this.value = vals;
        this.$emit('change', this.value);
        this.$emit('input', this.value);
      },
      findPath(val) {
        const children = this.props.children;
        const value = this.props.value;
        return _find(this.options);

        function _find(arr) {
          for (var i = 0; i < arr.length; i++) {
            if (arr[i][value] == val) {
              return arr[i].__index;
            } else if (arr[i].hasOwnProperty(children)) {
              return _find(arr[i][children]);
            }
          }
          return null;
        }
      },
      settingIndex() {
        const children = this.props.children;
        const value = this.props.value;
        __index(this.options, '');

        // 计算__index
        function __index(arr, _pIndex) {
          for (var i = 0; i < arr.length; i++) {
            arr[i]['__index'] = (_pIndex + "  " + arr[i][value]).trim();
            if (arr[i].hasOwnProperty(children)) {
              __index(arr[i][children], _pIndex + "  " + arr[i][value]);
            }
          }
        }
      },
    },
    watch: {
      '_inputValue'() {
        if (this.value != this._inputValue) {
          this.setValue();
        }
      },
      'options'() {
        //console.log("options");
        this.settingIndex();
      }
    },
  }
</script>

<style>
</style>
